package com.dfch.auto.appium.utils;

import com.dfch.auto.appium.main.AutoMainFrame;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ldcmaxim on 06/04/2018.
 */
public class AppiumStarter {

//    private static final Logger LOGGER = LoggerFactory.getLogger(AppiumStarter.class);

    public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            AutoMainFrame frame = new AutoMainFrame();

            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }


        /*
        Process process = null;
        try {
            String appiumCMD = " appium -a " + args[0] + " -p " + args[1] + " -bp " + args[2] + " --chromedriver-port " + args[3] + " -U " + args[4] + " --session-override";
//            LOGGER.debug("appium 启动命令:{}", appiumCMD);
            process = Runtime.getRuntime().exec(appiumCMD);
            InputStream in = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
//                LOGGER.info("appium创建进程:{}", line);
            }
        } catch (IOException e) {
//            LOGGER.error("创建Appium 服务端失败:", e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        */
    }

    public static Process build(String ip, int port, int bootstrapPort, int driverPort, String udid) {
        List<String> command = new ArrayList<>();
        String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        String classpath = System.getProperty("java.class.path");
        command.add(java);
        command.add("-classpath");
        command.add(classpath);
        command.add(AppiumStarter.class.getName());
        command.add(ip);
        command.add(String.valueOf(port));
        command.add(String.valueOf(bootstrapPort));
        command.add(String.valueOf(driverPort));
        command.add(udid);

        return build(command);


    }

    private static Process build(List<String> command) {
        Process process;
        try {
            ProcessBuilder builder = new ProcessBuilder(command);
            process = builder.start();

            System.out.println(builder.command());
        } catch (IOException e) {
            e.printStackTrace();
            process = null;
        }
        return process;
    }
}
